package com.jason.kotlin.meta.architecture1.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.jason.kotlin.meta.architecture1.ui.MetaConstant
import com.jason.kotlin.meta.R
import com.jason.kotlin.meta.architecture1.model.MetaImageBean
import com.jason.library.common.util.ScreenUtils

/**
 * Meta 的图片列表适配器
 * @author chenbaoyang
 */
class MetaImageAdapter(private val context: Context) :
    RecyclerView.Adapter<MetaImageAdapter.MetaImageViewHolder>() {

    var currentType = MetaConstant.META_IMAGE_TYPE_LINEAR

    private var dataList = mutableListOf<MetaImageBean>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        MetaImageViewHolder(
            LayoutInflater.from(context).inflate(R.layout.item_meta_image, parent, false)
        )

    override fun getItemCount() = dataList.size

    override fun onBindViewHolder(holder: MetaImageViewHolder, position: Int) {
        holder.updateSize(dataList[position], currentType)
        val options = RequestOptions().apply {
            fitCenter()
            placeholder(R.drawable.loading_bixue)
            error(R.drawable.loading_bixue)
            diskCacheStrategy(DiskCacheStrategy.ALL)
        }
        Glide.with(context).load(dataList[position].img).apply(options).into(holder.image)
    }


    fun setData(list: MutableList<MetaImageBean>) {
        list.let {
            dataList.clear()
            dataList.addAll(list)
            notifyDataSetChanged()
        }
    }

    fun addData(list: MutableList<MetaImageBean>) {
        list.let {
            dataList.addAll(list)
            notifyDataSetChanged()
        }
    }

    fun updateImageShowType(type: Int) {
        currentType = type
        notifyDataSetChanged()
    }



    class MetaImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val image: ImageView = itemView.findViewById(R.id.iv_meta_image)

        fun updateSize(bean: MetaImageBean, type: Int) {
            if(type == MetaConstant.META_IMAGE_TYPE_STAGE) {
                val width = ScreenUtils.getScreenWidth(itemView.context)/2 - ScreenUtils.dip2px(itemView.context, 20f)
                //进行原图片宽高比，进行计算实际空间高度，增加一个随机高度差
                val offset = (Math.random() * 100)
                val height = (width * bean.height) / bean.width
                image.layoutParams = LinearLayout.LayoutParams(width,height)
            }
        }
    }


}